package com.cspg.design.request;


import com.alibaba.fastjson.JSONObject;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.userInfoBean.UserInfoBean;
import com.cspg.design.common.Constant;
import com.cspg.design.dto.AuthUserDto;
import com.cspg.design.dto.RoleDto;
import com.cspg.design.http.IService;
import com.cspg.design.http.RetrofitUtil;
import com.cspg.design.model.PassVo;
import com.cspg.design.model.ResultVo;
import com.cspg.design.model.UserModel;
import com.cspg.design.presenter.LoginPresenter;
import com.cspg.design.utils.RSAUtils;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Login {

    private final RetrofitUtil retrofitUtil = new RetrofitUtil();
    private Call call;
    private final LoginPresenter presenter;
    private static final String type = "android";

    public Login(LoginPresenter presenter) {
        this.presenter = presenter;
    }

    public void loginNoCode(final  String username, final  String pwd) throws Exception
    {

        String encode_result = RSAUtils.encryptDataStr(pwd.getBytes(), RSAUtils.loadPublicKey(Constant.publicKey));
        AuthUserDto authUserDto = new AuthUserDto();
        authUserDto.setUsername(username);
        authUserDto.setPassword(encode_result);
        call = retrofitUtil.createReq(IService.class).login(authUserDto);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.getLoginFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }

                if (!response.isSuccessful()) {
                    try {
                        String  responseStr = response.errorBody().string();
                        ResultVo resultVo = JSONObject.parseObject(responseStr,ResultVo.class);
                        presenter.getLoginFailure(resultVo.getMessage());
                    }catch (Exception e)
                    {
                        presenter.getLoginFailure("登录出错");
                        e.printStackTrace();
                    }
                    return;
                }
                Object obj = response.body();
                UserModel userModel= (UserModel) response.body();
                if (null == userModel) {
                    presenter.getLoginFailure(Constant.HTTP_LOGIN_FAILURE);
                }
                else
                {
                    UserInfo userInfo = UserInfo.getInstance();
//                    userInfo.userName = userModel.getUser().getUser().getUsername();
                    userInfo.userName = userModel.getUser().getUser().getUsername();
                    userInfo.token = userModel.getToken();
                    userInfo.logon = "Y";
                    userInfo.password = encode_result;
                    userInfo.date = new Date();
                    userInfo.unit = userModel.getUser().getUser().getDept().getName();
                    UserInfo.setUserInfo(userInfo);
//                    for (RoleDto roleDto:userModel.getUser().getUser().getRoles())
//                    {
//                       if(roleDto.getName().contains("设计"))
//                        {
//                          userInfo.role ="设计";
//                        }
//                       else if (roleDto.getName().contains("施工"))
//                       {
//                           userInfo.role = "施工";
//                       }
//                    }
                    presenter.loginSuccess(userModel);
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                System.out.println("登录失败");
                presenter.getLoginFailure("登录失败");
            }
        });
    }

    public void updatePassword(final  String oldPass, final  String newPass) throws Exception
    {

        String encode_old = RSAUtils.encryptDataStr(oldPass.getBytes(), RSAUtils.loadPublicKey(Constant.publicKey));
        String encode_new = RSAUtils.encryptDataStr(newPass.getBytes(), RSAUtils.loadPublicKey(Constant.publicKey));
        PassVo passVo = new PassVo();
        passVo.setNewPass(encode_new);
        passVo.setOldPass(encode_old);
        retrofitUtil.setFirst(true);
        call = retrofitUtil.createReq(IService.class).updatePassword(passVo);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                if (null == response) {
                    presenter.getLoginFailure(Constant.HTTP_NO_NET_WORK);
                    return;
                }

                if (!response.isSuccessful()) {
                    try {
                        presenter.getLoginFailure(response.errorBody().string());
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                        presenter.getLoginFailure(Constant.HTTP_NO_NET_WORK);
                    }
                    return;
                }
                Object obj = response.body();
                if (null == obj) {
                    presenter.getLoginFailure(Constant.HTTP_LOGIN_FAILURE);
                }
                else
                {
                    presenter.updateSuccess("更新成功....");
                }
            }
            @Override
            public void onFailure(Call call, Throwable t) {
                System.out.println("登录失败");
                presenter.getLoginFailure("登录失败");
            }
        });
    }
    public RequestBody getRequestBody(HashMap<String, String> hashMap) {
        StringBuffer data = new StringBuffer();
        if (hashMap != null && hashMap.size() > 0) {
            Iterator iter = hashMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                data.append(key).append("=").append(val).append("&");
            }
        }
        String jso = data.substring(0, data.length() - 1);
        RequestBody requestBody =
                RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),jso);

        return requestBody;
    }
}
